package com.longy.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.longy.common.utils.PageUtils;
import com.longy.gulimall.product.service.CategoryBrandRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longy.common.utils.Query;

import com.longy.gulimall.product.dao.CategoryDao;
import com.longy.gulimall.product.entity.CategoryEntity;
import com.longy.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;
    @Resource
    private CategoryDao categoryDao;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String listWithTree = ops.get("listWithTree");
        if (StringUtils.isEmpty(listWithTree)) {
            List<CategoryEntity> categoryEntities = listWithTreeFormRedis();
            return categoryEntities;
        }
        List<CategoryEntity> categoryEntities = JSON.parseObject(listWithTree, new TypeReference<List<CategoryEntity>>(){});
        return categoryEntities;
    }
    private List<CategoryEntity> listWithTreeFormRedis() {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        //加分布式锁
        Boolean aTrue = ops.setIfAbsent("list:lock", "true", 1, TimeUnit.MINUTES);
        String listWithTree = ops.get("listWithTree");
        if (!StringUtils.isEmpty(listWithTree)) {
            return JSON.parseObject(listWithTree, new TypeReference<List<CategoryEntity>>(){});
        }
        try {
            if (aTrue) {
                List<CategoryEntity> categoryEntities = listWithTreeFormDB();
                String jsonString = JSON.toJSONString(categoryEntities);
                ops.set("listWithTree", jsonString);
                return categoryEntities;
            } else {
                Thread.sleep(1000);
                return listWithTreeFormRedis();
            }
        }catch (Exception e){
            System.out.println(e);
        }finally {
            stringRedisTemplate.delete("list:lock");
        }
        return null;
    }

    public List<CategoryEntity> listWithTreeFormDB() {
        System.out.println("查询数据库.....");
        //查询出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        List<CategoryEntity> level1Menus = categoryEntities.stream().filter(CategoryEntity ->
                CategoryEntity.getParentCid() == 0
        ).map((menu -> {
            menu.setChildren(getChildrens(menu, categoryEntities));
            return menu;
        })).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        //组装成树形结构
        return level1Menus;
    }

    /**
     * 找到catelogId的完整全部路径
     * 父-子-孙子 【2-25-225】
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        //添加进去的顺序是【225-25-2】，需要集合工具转换
        Collections.reverse(parentPath);
        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }

    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())){
            categoryBrandRelationService.categoryBrandRelation(category.getCatId(),category.getName());

        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public void update(CategoryEntity category) {
        CategoryEntity byId = this.getById(category.getCatId());
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Integer sort = byId.getSort() + 1;
        byId.setSort(sort);
        boolean b = this.updateById(byId);
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            paths = findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }


    //递归查找所有子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(CategoryEntity -> {
            return CategoryEntity.getParentCid() == root.getCatId();
        }).map(CategoryEntity -> {
            //1.找到子菜单
            CategoryEntity.setChildren(getChildrens(CategoryEntity, all));
            return CategoryEntity;
        }).sorted((menu1, menu2) -> {
            //2.进行排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}